#!/usr/bin/env node

const fs = require('fs');
const path = require('path');
const Base64 = require('js-base64').Base64;

const fnActualFile = require('./utils/fnActualFile')

const passInName = process.argv.slice(-1)[0];
// console.log(Object.prototype.toString.call(process.argv));

const fnHashRule = function (s) {
    return Base64.encode(s).substr(0, 5);
};
const htmlIdHashSrcArgu = process.argv[3] || '';
const htmlIdHashReg = /^--hash-src=([-\w]+)$/;

function checkhtmlIdHashSrcArgu() {
    if (htmlIdHashReg.test(htmlIdHashSrcArgu)) {
        console.error('指定hash只能用以下格式: “--hash-src=hashSrc”, 等号后必须是字母，数字，下划线或者短横线.');
    }
}

checkhtmlIdHashSrcArgu();

console.log('vue-sass-cli is creating the directory structure for static-html-sub-compile.');

function checkPassInName() {
    if (/^(?:[-_\.0-9]|[-_\.0-9])$/.test(passInName)) {
        console.error('项目名不能以“－”或“_”或“.”结尾, 请修改.');
    }
    if (/[-_][-_]/.test(passInName)) {
        console.error('项目名不能包含连续的“－” 或/和 “_”,　请修改.');
    }
    if (!/[\w\-\.]+/.test(passInName)) {
        console.error('项目名不能包含连续的只能由大小写字母、数字、“－”、“_”组成,　请修改.');
    }
    if (/-/.test(passInName) && /[A-Z]/.test(passInName)) {
        console.error('项目名不能同时包含“－”和大写字母,　请修改.');
    }
    if (/[\u4e00-\u9fa5]/.test(passInName)) {
        console.error('项目名不能包含的中文字符,　请修改.')
    }
}

checkPassInName();

function computeNames() {
    let hyphenName = '';
    let pascalCaseName = '';
    let camelCaseName = '';
    let htmlIdHash = '';
    if (/-/.test(passInName)) {
        hyphenName = passInName;
        tmpCamelCase = passInName.replace(/-([a-z])/g, function () {
            return arguments[1].toUpperCase();
        });
    } else {
        hyphenName = passInName.replace(/([A-Z])/g, function () {
            return '-' + arguments[1].toLowerCase();
        });
        tmpCamelCase = passInName;
    }
    pascalCaseName = tmpCamelCase.replace(/^([a-zA-Z])/, function () {
        return arguments[1].toUpperCase()
    });
    camelCaseName = tmpCamelCase.replace(/^([a-zA-Z])/, function () {
        return arguments[1].toLowerCase()
    });
    htmlIdHash = htmlIdHashSrcArgu.replace(/--hash-src=([-\w]+)/, function () {
        return '--' + fnHashRule(arguments[1]);
    });
    return {
        passInName,
        hyphenName,
        pascalCaseName,
        camelCaseName,
        htmlIdHash,
    }
}

const names = computeNames();

const argv = require('yargs').argv;
let srcDirectory = argv.template || 'template.d';
// console.log(srcDirectory);
// console.log('above is the srcDirectory, is it right?');
const validTemplates = require('./config.js').templates;
// console.log(validTemplates);
// console.log('above is the validTemplates, is it right?');
if(validTemplates.indexOf(srcDirectory) === -1){
    const msg = `Only these template are avlid: ${validTemplates.join(',\n')}.`;
    console.log(msg);
    throw 'But other template was specialed: ' + srcDirectory;
}
//console.log(`This template will be used: ${path.resolve(srcDirectory)}.`);
console.log(`This template will be used: ${__dirname + '/' + srcDirectory}.`);
srcDirectory = './' + srcDirectory;
const distDirectory = './' + names.passInName;
const stableDirBasename = '.stable';
const srcStableDirectory = srcDirectory + '/' + stableDirBasename;
const distStableDirectory = distDirectory + '/' + stableDirBasename;

const template = {
    sass: require(srcDirectory + '/component-name.sass.js'),
    vue: require(srcDirectory + '/componentName.vue.js'),
    js: require(srcDirectory + '/componentName.js.js'),
    html: require(srcStableDirectory + '/template.html.js'),
    scss: require(srcStableDirectory + '/index.scss.js'),
};

function fnGenTaskObj() {
    const replaceStrPairsObj = {
        'componentName': names.camelCaseName,
        'component-name': names.hyphenName,
        '--hash': names.htmlIdHash,
    };
    const fsActionObj = {
        createDirSync(newDirPath) {
            return new Promise((resolve, reject) => {
                fs.mkdir(newDirPath, (err)=>{
                    if(err) reject(err);
                    resolve(newDirPath + ' directory has been created.');
                });
            });
        },
        genActualFile(srcPath, distinationPath, replaceStrPairsObj) {
            fnActualFile(...arguments)();
        }
    };
    fsActionObj.createDirSync(names.passInName).then(function (msg) {
            fsActionObj.genActualFile(template['js'], `${distDirectory}/${names.camelCaseName}.js`, replaceStrPairsObj);
            fsActionObj.genActualFile(template['vue'], `${distDirectory}/${names.camelCaseName}.vue`, replaceStrPairsObj);
            fsActionObj.genActualFile(template['sass'], `${distDirectory}/${names.camelCaseName}.sass`, replaceStrPairsObj);
            fsActionObj.createDirSync(distStableDirectory).then(function (msg) {
            fsActionObj.genActualFile(template['scss'], `${distStableDirectory}/index.scss`, replaceStrPairsObj);
            fsActionObj.genActualFile(template['html'], `${distStableDirectory}/template.html`, replaceStrPairsObj);
        })
    }).then(function () {
        console.log(`Done! ${distDirectory} was generated!`);
    }).catch(err=>{
        console.log(err);
    });
}

fnGenTaskObj();
